// filename: frontend/src/store/player.js

import { defineStore } from "pinia";
import { computed, ref } from "vue";

const audioContext = uni.createInnerAudioContext();

// #ifdef H5
audioContext.obeyMuteSwitch = false;
// #endif

export const usePlayerStore = defineStore("player", () => {
  // --- 核心状态 ---
  const playlist = ref([]);
  const currentSongIndex = ref(-1);
  const isPlaying = ref(false);
  const currentTime = ref(0);
  const duration = ref(0);
  const playMode = ref("loop");
  const showPlayer = ref(false);

  // --- 计算属性 ---
  const currentSong = computed(() => {
    if (currentSongIndex.value >= 0 && playlist.value.length > 0) {
      return playlist.value[currentSongIndex.value];
    }
    return null;
  });

  const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
  
  // --- 内部辅助函数 ---
  const _playAudio = () => {
    if (!currentSong.value?.id) {
      return;
    }
    currentTime.value = 0;
    duration.value = 0;
    audioContext.src = `${API_BASE_URL}/api/audio-stream/${currentSong.value.id}`;
    audioContext.play();
  };

  // --- 核心动作 ---
  const setPlaylistAndPlay = (newPlaylist, songId) => {
    playlist.value = newPlaylist;
    const index = playlist.value.findIndex((song) => song.id === songId);
    if (index !== -1) {
      currentSongIndex.value = index;
      _playAudio();
      showPlayer.value = true;
    }
  };

  const togglePlay = () => {
    if (!currentSong.value) {
      return;
    }
    if (isPlaying.value) {
      audioContext.pause();
    } else {
      audioContext.play();
    }
  };

  const seek = (time) => {
    if (!Number.isNaN(time)) {
      audioContext.seek(time);
    }
  };

  const playNext = () => {
    if (playlist.value.length === 0) {
      return;
    }
    let nextIndex = 0;
    if (playMode.value === "random") {
      if (playlist.value.length > 1) {
        do {
          nextIndex = Math.floor(Math.random() * playlist.value.length);
        } while (nextIndex === currentSongIndex.value);
      }
    } else {
      nextIndex = currentSongIndex.value + 1;
      if (nextIndex >= playlist.value.length) {
        nextIndex = 0;
      }
    }
    currentSongIndex.value = nextIndex;
    _playAudio();
  };

  const playPrev = () => {
    if (playlist.value.length === 0) {
      return;
    }
    let prevIndex = 0;
    if (playMode.value === "random") {
      if (playlist.value.length > 1) {
        do {
          prevIndex = Math.floor(Math.random() * playlist.value.length);
        } while (prevIndex === currentSongIndex.value);
      }
    } else {
      prevIndex = currentSongIndex.value - 1;
      if (prevIndex < 0) {
        prevIndex = playlist.value.length - 1;
      }
    }
    currentSongIndex.value = prevIndex;
    _playAudio();
  };

  const changePlayMode = () => {
    const modes = ["loop", "single", "random"];
    const currentModeIndex = modes.indexOf(playMode.value);
    const nextModeIndex = (currentModeIndex + 1) % modes.length;
    playMode.value = modes[nextModeIndex];
  };

  const closePlayer = () => {
    audioContext.stop();
    showPlayer.value = false;
    currentSongIndex.value = -1;
    playlist.value = [];
    isPlaying.value = false;
    currentTime.value = 0;
    duration.value = 0;
  };

  // --- 事件监听器 ---
  audioContext.onPlay(() => {
    isPlaying.value = true;
  });
  audioContext.onPause(() => {
    isPlaying.value = false;
  });
  audioContext.onStop(() => {
    isPlaying.value = false;
    currentTime.value = 0;
  });

  audioContext.onEnded(() => {
    if (playMode.value === "single") {
      _playAudio();
    } else {
      playNext();
    }
  });

  audioContext.onError((_err) => {
    isPlaying.value = false;
  });

  audioContext.onTimeUpdate(() => {
    currentTime.value = audioContext.currentTime;
    // 只有在第一次获取到有效时长时才更新
    if (duration.value === 0 && audioContext.duration > 0) {
      duration.value = audioContext.duration;
    }
  });

  audioContext.onCanplay(() => {
    // 使用一个延迟来确保获取到的是稳定的时长
    setTimeout(() => {
      if (audioContext.duration > 0) {
        duration.value = audioContext.duration;
      }
    }, 200);
  });

  // onSeeked 和 onSeeking 不再需要特殊处理，
  // 因为 Nginx 已经保证了 Range Request 的正确性。
  // uni-app 会在 seek 后自动触发 onTimeUpdate。

  return {
    playlist,
    currentSongIndex,
    isPlaying,
    currentTime,
    duration,
    playMode,
    showPlayer,
    currentSong,
    setPlaylistAndPlay,
    togglePlay,
    playNext,
    playPrev,
    changePlayMode,
    seek,
    closePlayer,
  };
});
